package com.example.playbox

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.playbox.bean.Game
import com.example.playbox.utils.MySQLiteOpenHelper

class AddGamesActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var etGameId: EditText
    private lateinit var etGameName: EditText
    private lateinit var etGameTime: EditText
    private lateinit var etGameNote: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_games)
        initView()
    }

    private fun initView() {
        etGameId = findViewById(R.id.et_gameid)
        etGameName = findViewById(R.id.et_gamename)
        etGameTime = findViewById(R.id.et_gametime)
        etGameNote = findViewById(R.id.et_gamenote)

        val btnAdd: Button = findViewById(R.id.btn_add)
        btnAdd.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        val gameId = etGameId.text.toString().trim()
        val gameName = etGameName.text.toString().trim()
        val gameTime = etGameTime.text.toString().trim()
        val gameNote = etGameNote.text.toString()
        val userName = getCurrentUsername()

        if (TextUtils.isEmpty(gameId)) {
            Toast.makeText(this, "请输入游戏id", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(gameName)) {
            Toast.makeText(this, "请输入游戏名称", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(gameTime)) {
            Toast.makeText(this, "请输入约玩时间", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(gameNote)) {
            Toast.makeText(this, "请输入备注", Toast.LENGTH_SHORT).show()
            return
        }

        val game = Game(gameId, gameName, gameTime, gameNote, userName)
        val dao = MySQLiteOpenHelper(applicationContext)
        dao.open()
        val result = dao.addGames(game)

        if (result > 0) {
            Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "发布失败", Toast.LENGTH_SHORT).show()
        }
        dao.close()
        finish()
    }

    private fun getCurrentUsername(): String {
        val sp = getSharedPreferences("loginInfo", MODE_PRIVATE)
        return sp.getString("loginUserName", "") ?: ""
    }
}